<template>
  <div>
    <a-card class="card">
      <div style="display:flex;align-items: center;">
        <a-upload
          name="file"
          action="#"
          :beforeUpload="beforeUpload"
        >
          <a-button> <a-icon type="upload" /> 导入 </a-button>
        </a-upload>
        <a-popconfirm title="确定删除所有数据?" ok-text="确定" cancel-text="取消" @confirm="deleteAllConfirm" style="margin-left:10px;">
          <a-button type="danger">删除所有</a-button>
        </a-popconfirm>
        <!-- <a-input-search placeholder="搜索姓名" enter-button @search="getData" v-model="keyWord" style="width:200px;margin-left:10px;" /> -->
        <a-select v-model="keyWord" style="width: 160px;margin-left:10px;" @change="getData" clear>
          <a-select-option :value="''" >
            全部
          </a-select-option>
          <a-select-option :value="item" v-for="(item,index) in accountList" :key="index" >
            {{item}}
          </a-select-option>
        </a-select>
        <a-range-picker
        :ranges="{ '昨天': [moment().add(-1, 'days'), moment().add(-1, 'days')], '过去7天': [moment().add(-7, 'days'), moment().add(-1, 'days')], 
                    '过去30天': [moment().add(-30, 'days'), moment().add(-1, 'days')] }"
          :disabled-date="disabledDate" @change="formDateChange"  style="width:240px;margin-left:10px;" 
        />
      </div>
      <a-table rowKey="id" :columns="columns" :data-source="data" bordered style="margin-top:20px" :loading="loading">
        <template
          v-for="col in ['name', 'product','quantity', 'quality', 'price', 'monthTarget', 'date']"
          :slot="col"
          slot-scope="text, record"
        >
          <div :key="col">
            <a-input
              v-if="record.editable"
              style="margin: -5px 0"
              :value="text"
              @change="e => handleChange(e.target.value, record.key, col)"
            />
            <template v-else>
              {{ text }}
            </template>
          </div>
        </template>
        <template slot="operation" slot-scope="text, record">
          <div class="editable-row-operations">
            <span v-if="record.editable">
              <a @click="() => save(record.key)" style="margin-right:10px">保存</a>
              <a-popconfirm title="确认关闭?" @confirm="() => cancel(record.key)">
                <a>关闭</a>
              </a-popconfirm>
            </span>
            <span v-else>
              <a :disabled="editingKey !== ''" @click="() => edit(record.key)">编辑</a>
              <a-popconfirm :disabled="editingKey !== ''" title="确定删除当前数据?" ok-text="确定" cancel-text="取消" @confirm="deleteOne(record.key)" style="margin-left:6px;">
                <a :disabled="editingKey !== ''" >删除</a>
              </a-popconfirm>
            </span>
          </div>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script>
import xlsx from 'xlsx';
import {uploadExcelData, getDataList, updateData, clearData, deleteData, getNames} from '@/api/shumei/shumei'
import moment from 'moment';

const columns = [
  {
    title: '姓名',
    dataIndex: 'name',
    width: '10%',
    scopedSlots: { customRender: 'name' },
  },
  {
    title: '产品',
    dataIndex: 'product',
    width: '10%',
    scopedSlots: { customRender: 'product' },
  },
  {
    title: '制作数',
    dataIndex: 'quantity',
    width: '10%',
    scopedSlots: { customRender: 'quantity' },
  },
  {
    title: '中视频数量',
    dataIndex: 'quality',
    width: '10%',
    scopedSlots: { customRender: 'quality' },
  },
  {
    title: '金额',
    dataIndex: 'price',
    width: '10%',
    scopedSlots: { customRender: 'price' },
  },
  {
    title: '任务金额',
    dataIndex: 'monthTarget',
    width: '10%',
    scopedSlots: { customRender: 'monthTarget' },
  },
  {
    title: '时间',
    dataIndex: 'date',
    width: '20%',
    scopedSlots: { customRender: 'date' },
  },
  {
    title: '编辑',
    dataIndex: 'operation',
    scopedSlots: { customRender: 'operation' },
  },
];

const data = [];

export default {
  data() {
    this.cacheData = data.map(item => ({ ...item }));
    return {
      moment,
      columns,
      data:[],
      editingKey: '',
      keyWord: '',
      start_date: "",
      end_date: "",
      loading: false,
      accountList: [],
    }
  },
  created(){
    this.getNames()
    this.getData()
  },
  methods:{
    getData(){
      let params = {
        filter_name: this.keyWord,
        start_date: this.start_date,
        end_date: this.end_date,
      }
      this.loading = true
      getDataList(params).then((res) => {
        this.loading = false
        if(res.errcode == 0){
          for(let item of res.data){
            item['key'] = item['id'].toString()
          }
          this.data = res.data
          this.cacheData = res.data.map(item => ({ ...item }));
        }
      }).catch(()=>{
        this.loading = false
      });
    },
    getNames(){
      getNames({}).then((res) => {
        if(res.errcode == 0){
          this.accountList = res.data
        }
      });
    },
    formDateChange(e){
      console.log(e)
      if(e.length > 0){
        this.start_date = e[0].format("YYYY-MM-DD")
        this.end_date = e[1].format("YYYY-MM-DD")
      }else{
        this.start_date = ""
        this.end_date = ""
      }
      this.getData()
    },
    async beforeUpload(file) {
      // console.log(file)
      let dataBinary = await new Promise((resolve) => {
        // Web API构造函数FileReader，可实例化对象，去调用其身上方法，去读取解析文件信息
        let reader = new FileReader(); // https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader
        reader.readAsBinaryString(file)
        // console.log("实例化对象有各种方法", reader);
        reader.onload = (ev) => {
          // console.log("文件解析流程进度事件", ev);
          resolve(ev.target.result); // 将解析好的结果扔出去，以供使用
        };
      });
      
      let workBook = xlsx.read(dataBinary, {type: 'binary', cellDates: true})
      let workSheet = workBook.Sheets[workBook.SheetNames[0]]
      const data = xlsx.utils.sheet_to_json(workSheet)
      let excelData = []
      console.log(data)
      for(let item of data){
        if(item['姓名']){
          item['date'] = item['日期']
          item['product'] = item['品名']
          item['num'] = item['总数量']
          item['price'] = item['达成金额']
          item['quality'] = item['中视频数量']
          item['name'] = item['姓名'];
          delete data['日期'];delete data['品名'];delete data['总数量'];delete data['达成金额'];delete data['姓名'];delete data['中视频数量'];
          excelData.push(item)
        }
      }
      this.loading = true
      uploadExcelData({excelData: excelData}).then((res) => {
        if(res.errcode == 0){
          this.getData();
        }
      }).catch(err=>{
        if(err.errcode == '40001'){
          this.getData();
        }
      });
      return Promise.reject();
    },
    uploadChange(info){
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        this.$message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} file upload failed.`);
      }
    },
    handleChange(value, key, column) {
      const newData = [...this.data];
      const target = newData.find(item => key === item.key);
      if (target) {
        target[column] = value;
        this.data = newData;
      }
    },
    edit(key) {
      const newData = [...this.data];
      const target = newData.find(item => key === item.key);
      this.editingKey = key;
      if (target) {
        target.editable = true;
        this.data = newData;
      }
    },
    save(key) {
      const newData = [...this.data];
      const newCacheData = [...this.cacheData];
      const target = newData.find(item => key === item.key);
      const targetCache = newCacheData.find(item => key === item.key);
      if (target && targetCache) {
        delete target.editable;
        let data = JSON.parse(JSON.stringify(target))
        delete data['key']
        updateData({data:[data]}).then((res) => {
          if(res.errcode == 0){
            this.data = newData;
            Object.assign(targetCache, target);
            this.cacheData = newCacheData;
            this.editingKey = '';
            this.getData()
          }
        });
      }
      
    },
    cancel(key) {
      const newData = [...this.data];
      const target = newData.find(item => key === item.key);
      this.editingKey = '';
      if (target) {
        Object.assign(target, this.cacheData.find(item => key === item.key));
        delete target.editable;
        this.data = newData;
      }
    },
    disabledDate(current){
      return current && current > moment().endOf('day');
    },
    deleteOne(key){
      const newData = [...this.data];
      const target = newData.find(item => key === item.key);
      if (target) {
        this.loading = true
        deleteData({ids: target.id}).then((res) => {
          if(res.errcode == 0){
            this.$message.success("删除成功")
            this.getData()
          }
        });
      }
    },
    deleteAllConfirm(){
      this.loading = true
      clearData({clear: 1}).then((res) => {
        if(res.errcode == 0){
          this.$message.success("删除成功")
          this.getData()
        }
      });
    },
  },
  computed:{
    token(){
      return this.$store.state.user.userInfo.token
    }
  }
}
</script>

<style lang="less" scoped>

</style>
